<?php

App::uses('AppController', 'Controller');
App::uses('Security', 'Utility');

class MemberController extends AppController {

	public $uses = array('Member');

	public function index() {

		$list = $this->Member->find('all', array('order' => 'id DESC'));
		$this->set('list', $list);
	}
	
	function afterFilter()
	{
		$data =  $this->Session->read('User');
		
		if( $data['Member']['type'] != '0')
		{
			return $this->redirect('/');
		}
	}
	
	public function edit() {
	
		if ($this->request->is('post')) {
				
			if($this->request->data['Member']['password'] == '') {
				
				$data = array('id' => $this->request->data['Member']['id'],
						'email' => $this->request->data['Member']['email'],
						'type' => $this->request->data['Member']['type']);
				
				$this->Member->save($data);
				
			} else {
				$data = array('id' => $this->request->data['Member']['id'], 
							'password' => Security::hash($this->request->data['Member']['password']), 
							'email' => $this->request->data['Member']['email'], 
							'type' => $this->request->data['Member']['type']);
				
				$this->Member->save($data);
			}
			
			$this->Session->setFlash('Update member info success !', 'flash_custom');
				
			return $this->redirect('/member');
		} else {
				
			$id = $_GET['id'];
			$data = $this->Member->find('first', array('conditions' => array('id' => $id)));
			$this->set('data', $data);
		}
	
	}
	
	public function add() {
		
		if ($this->request->is('post')) {
	
			$validate = $this->Member->find('first', array('conditions' => array('email' => $this->request->data['Member']['email'])));
			
			if($validate != null) {
				
				// Set a session flash message and redirect.
				$this->Session->setFlash('Someone already has that email. Try another ?', 'flash_custom_error');
				
				return $this->redirect('/member/add');
			} else {
				
				$this->request->data['Member']['password'] = Security::hash($this->request->data['Member']['password']);
				
				// If the form data can be validated and saved...
				if ($this->Member->save($this->request->data)) {
				
					// Set a session flash message and redirect.
					$this->Session->setFlash('Add new member success !', 'flash_custom');
				
					return $this->redirect('/member/add');
				}
			}			
		}
	}
	
	public function active() {
	
		$id = $_GET['id'];
	
		$data = array('id' => $id, 'delete_flg' => '0');
	
		// This will update Recipe with id 10
		$this->Member->save($data);
	
		return $this->redirect('/member');
	}
	
	public function delete() {
	
		$id = $_GET['id'];
	
		$data = array('id' => $id, 'delete_flg' => '1');
	
		// This will update Recipe with id 10
		$this->Member->save($data);
	
		return $this->redirect('/member');
	}
}
